import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/home.vue";
import store from "@/store";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "home",
    component: Home,
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login.vue"),
  },
];
const router = new VueRouter({
  routes,
});

// 导航守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = router.app.$options.store.state.user.token;
  // store.state.user.token
  // localStorage.getItem("token");

  if (to.name !== "login" && !isAuthenticated) {
    next({ name: "login" }); // 未登录，重定向到登录页面
  } else {
    next(); // 已登录或访问登录页面，放行
  }
});

export default router;
